#pragma

#include <iostream>
#include <pthread.h>
#include <vector>
#include <string>
#include <queue>
#include <unistd.h>
#include "thread.hpp"
using namespace std;
struct ThreadInfo
{
    pthread_t tid;
    string name;
};

// 默认为线程池中有多少线程
static const int defaultnum = 5;
template <class T>
class ThreadPool
{
public:
    void Lock()
    {
        pthread_mutex_lock(&_mutex);
    }
    void unLock()
    {
        pthread_mutex_unlock(&_mutex);
    }
    void wakeup()
    {
        // 唤醒
        pthread_cond_signal(&_cond);
    }
    void Threadsleep()
    {
        // 阻塞等待
        pthread_cond_wait(&_cond, &_mutex);
    }
    bool isQueueEmpty()
    {
        return tasks.empty();
    }
    string Getname(pthread_t tid)
    {
        for (auto ti : threads)
        {
            if (ti->Tid() == tid)
                return ti->Name();
        }
        return "none";
    }

public:
 
    ThreadPool(int num = defaultnum)
        : threads(num)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }
    
    //静态成员函数作为中间层
    static void StaticHandlerTask(void*args)
    {
        ThreadPool<T>*pool=static_cast<ThreadPool<T>*>(args);
        pool->HandlerTask();
    }
    
    //类成员函数无法直接作为普通函数指针传递（成员函数隐含 this 指针参数，与 void(*)() 类型不匹配）
    void HandlerTask()
    {
        string name = Getname(pthread_self());
        while (1)
        {
            Lock();
            // 避免错误唤醒的问题
            while (isQueueEmpty())
            {
                Threadsleep();
            }
            T t = Pop();
            unLock();
            t(); // Task.hpp中的仿函数，在锁外可以并发执行任务
            cout << name << " run,result:" << t.Getresult() << endl;
        }
    }

    void start()
    {
        int num = threads.size();
        for (int i = 0; i < num; i++)
        {
            //不可这样直接调用，普通函数指针与非静态函数指针存在本质区别
            //threads[i] = new Thread({HandlerTask,this,pthread_self()});
            threads[i] = new Thread({StaticHandlerTask,this});
            threads[i]->Run();
        }
    }

    T Pop()
    {
        T t = tasks.front();
        tasks.pop();
        return t;
    }
    void Push(const T &t)
    {
        Lock();
        tasks.push(t);
        wakeup();
        unLock();
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
        for(int i=0;i<threads.size();i++)
        {
            delete threads[i];
        }
    }

private:
    vector<Thread *> threads; // 用于维护线程,创建多个线程对象
    queue<T> tasks;           // 需要处理任务的等待队列
    pthread_mutex_t _mutex;
    pthread_cond_t _cond;
};